import asyncio
import json

import aioredis
import pandas as pd

import config


#
# # 原始数据
# crypto_data = {
#     "2023-10-01 12:00": [
#         {"BTC": 50000},
#         {"ETH": 3000},
#         {"LTC": 200}
#     ],
#     "2023-10-01 13:00": [
#         {"BTC": 51000},
#         {"ETH": 3100},
#         {"DOGE": 0.5}
#     ]
# }
#
# # 重组数据
# processed = []
# for timestamp, prices in crypto_data.items():
#     row = {"timestamp": timestamp}
#     for crypto in prices:
#         row.update(crypto)
#     processed.append(row)
# print( processed)
# # 创建DataFrame
# df = pd.DataFrame(processed).set_index("timestamp")
# df.index = pd.to_datetime(df.index)  # 转换时间格式
#
# print(df)

async def market_warning(redis):
    processed = []
    data_list = await redis.lrange(config.REDIS_KEY_NAMES['all_price_every_time'], 0, -1)
    for data in data_list:
        data = json.loads(data)
        for k, v in data.items():
            if k != 'timestamp':
                data[k] = float(v[0])
            else:
                k = v
        temp = {'timestamp': data['timestamp'], 'GRASSUSDT': data['GRASSUSDT'], 'BTCUSDT': data['BTCUSDT']}
        processed.append(data)
    df = pd.DataFrame(processed).set_index("timestamp")
    df.index = pd.to_datetime(df.index, unit='s', utc=True).tz_convert('Asia/Shanghai')
    # df_reset = df.reset_index()
    # df_long = df.melt(id_vars=['timestamp'], var_name='币种', value_name='价格')
    # df['returns'] = df.groupby('symbol')['price'].pct_change()
    # df_pct = df.pct_change(periods=1)
    # print(df_pct)
    # print(df_long)
    print(df)

async def main():
    redis = aioredis.from_url(
        f"redis://:{config.REDIS_CONFIG['password']}@{config.REDIS_CONFIG['host']}:{config.REDIS_CONFIG['port']}/{config.REDIS_CONFIG['db']}"
        , encoding="utf-8", decode_responses=True
    )
    await market_warning(redis)


asyncio.run(main())
